/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.letmeshare.pedagogue.core.module;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.letmeshare.pedagogue.core.entities.Organization;
import org.letmeshare.pedagogue.core.entities.Party;
import org.letmeshare.pedagogue.core.entities.Role;
import org.letmeshare.pedagogue.core.validation.BusinessValidationException;

/**
 *
 * @author ibisuser1
 */
public class OrganizationModule extends AbstractModule{
    
    public static void createOrganization (EntityManager em, Organization organization) {
        checkEntityManager(em);
        if (organization == null) {
            throw new IllegalArgumentException("Organization required");
        }
        organization.validate();
        em.persist(organization);
    }
    
    public static void updateOrganization (EntityManager em, Organization organization) {
        checkEntityManager(em);
        if (organization == null) {
            throw new IllegalArgumentException("Organization required");
        }
        if (getOrganization(em, organization.getUid()) == null) {
            throw new BusinessValidationException("Organization doesn't exist");
        }
        em.merge(organization);
    }
    
    public static Organization getOrganization(EntityManager em, String orgId) {
        checkEntityManager(em);
        return em.find(Organization.class, orgId);
    }
    
    public static Set<Role> getAvailableRoles(EntityManager em, String orgId) {
        checkEntityManager(em);
        if (orgId == null) {
            throw new IllegalArgumentException("OrgId required");
        }
        Query query = em.createNamedQuery(Organization.GET_AVAILABLE_ROLES);
        query.setParameter(Organization.ORG_ID, orgId);
        List availableRoles = query.getResultList();
        return availableRoles == null ? null : new HashSet<Role>(availableRoles);
    }
    
    public static void addRole (EntityManager em, Role role, String orgId) {
        checkEntityManager(em);
        if (role == null) {
            throw new IllegalArgumentException("Role required");
        }
        role.validate();
        if (!role.getName().matches(".+\\..+")) {
            role.setName(orgId + "." + role.getName());
        }
        Set<Role> availableRoles = getAvailableRoles(em, orgId);
        if (availableRoles != null && availableRoles.contains(role)) {
            throw new BusinessValidationException("Duplicate Role");
        }
        em.persist(role);
    }
    public static Party getParty(EntityManager em,String userId){
        return null;
    }
}
